package demo1;

/**
 * @Author liangzai
 * @Description:
 */
public class Training {
    //最小路径和
    public int minPathSum(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int[][] dp = new int[n+1][m+1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if(j==1){
                    dp[i][j] = dp[i-1][j] + grid[i-1][j-1];
                }else if(i==1){
                    dp[i][j] = dp[i][j-1] + grid[i-1][j-1];
                }else {
                    dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i - 1][j - 1];
                }
            }
        }
        return dp[n][m];
    }

    //下降路径最小和
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        int[][] dp = new int[n+2][m+2];
        for (int i = 1; i <= n; i++) {
            dp[i][0] = Integer.MAX_VALUE;
            dp[i][m+1] = Integer.MAX_VALUE;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                dp[i][j] = Math.min(Math.min(dp[i-1][j-1],dp[i-1][j]),dp[i-1][j+1]) + matrix[i-1][j-1];
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 1; i <= m; i++) {
            min = Math.min(min,dp[n][i]);
        }
        return min;
    }
}
